package com.lanmaoly.web.config;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.lanmaoly.web.handler.MyAuthenticationFailureHandler;
import com.lanmaoly.web.handler.MyAuthenticationSucessHandler;
import com.lanmaoly.web.server.entity.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.DefaultRedirectStrategy;
import org.springframework.security.web.RedirectStrategy;
import org.springframework.security.web.authentication.rememberme.JdbcTokenRepositoryImpl;
import org.springframework.security.web.authentication.rememberme.PersistentTokenRepository;
import org.springframework.security.web.firewall.DefaultHttpFirewall;
import org.springframework.security.web.firewall.HttpFirewall;

import javax.servlet.http.HttpServletResponse;
import javax.sql.DataSource;
import java.io.PrintWriter;

/**
 * 认证类
 *
 * @author Administrator
 */
@Slf4j
@Configuration
@EnableWebSecurity
public class PorcelainSecurityConfig extends WebSecurityConfigurerAdapter {
    @Autowired
    private ObjectMapper mapper;
    @Autowired
    private UserDetailsServiceImpl userDetailsService;
    @Autowired
    private MyAuthenticationSucessHandler authenticationSucessHandler;
    @Autowired
    private MyAuthenticationFailureHandler authenticationFailureHandler;
    @Autowired
    private DataSource dataSource;
    private RedirectStrategy redirectStrategy = new DefaultRedirectStrategy();

    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

    @Bean
    public PersistentTokenRepository persistentTokenRepository() {
        JdbcTokenRepositoryImpl jdbcTokenRepository = new JdbcTokenRepositoryImpl();
        jdbcTokenRepository.setDataSource(dataSource);
        jdbcTokenRepository.setCreateTableOnStartup(false);
        return jdbcTokenRepository;
    }

    @Bean
    public HttpFirewall defaultHttpFirewall() {
        return new DefaultHttpFirewall();
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.formLogin() // 表单登录
                // http.httpBasic() // HTTP Basic
                .loginPage("/authentication/require") // 登录跳转 URL
                .loginProcessingUrl("/login") // 处理表单登录 URL
                .successHandler(authenticationSucessHandler) // 处理登录成功
                .failureHandler(authenticationFailureHandler) // 处理登录失败
                .and()
                .rememberMe()
                .tokenRepository(persistentTokenRepository()) // 配置 token 持久化仓库
                .tokenValiditySeconds(3600) // remember 过期时间，单为秒
                .userDetailsService(userDetailsService) // 处理自动登录逻辑
                .and()
                .authorizeRequests() // 授权配置
                // 无需认证的请求路径
                .antMatchers("/authentication/require",
                        "/",
                        "/index",
                        "/register/**",
                        "/forget/**",
                        "/upload/**",
                        "/itemSearch/**",
                        "/settle/**",
                        "/cart/**",
                        "/data/**",
                        "/fonts/**",
                        "/img/**",
                        "/image/**",
                        "/js/**",
                        "/plugins/**",
                        "/css/**")
                .permitAll()
                .anyRequest()  // 所有请求
                .authenticated() // 都需要认证
                .and()
                .csrf().disable()
                .exceptionHandling()
//                .accessDeniedHandler()
                .authenticationEntryPoint((request, response, authException) -> {
                    String method = request.getMethod();
                    log.info("commence method: {}", method);
                    if ("post".equalsIgnoreCase(method)) {
                        // post 返回json
                        response.setContentType("application/json;charset=utf-8");
                        response.setStatus(HttpServletResponse.SC_FORBIDDEN);
                        PrintWriter out = response.getWriter();
                        Result result = Result.fail("请登录");
                        out.write(mapper.writeValueAsString(result));
                        out.flush();
                        out.close();
                    } else {
                        // get 重定向
                        redirectStrategy.sendRedirect(request, response, "/authentication/require");
                    }
                }).and().logout().logoutSuccessUrl("/index");
    }

}
